#!/usr/bin/env python

import sys, getopt
import syscons


def usage():
    print "Usage: convert_keymap [-i input_keymap] [-o output_keymap] unicode_map"


if __name__ == "__main__":

    # parse command options
    try:
        opts, args = getopt.getopt(sys.argv[1:], "i:o:h", ["help", ])
    except getopt.GetoptError, err:
        print str(err)
        sys.exit(2)

    if len(args) < 1:
        usage()
        sys.exit(2)
    unicode_map_files = []
    unicode_map_files.extend(args)

    input_keymap_file = None
    output_keymap_file = None

    for o, a in opts:
        if o == '-h' or o == '--help':
            usage()
            sys.exit(0)
        elif o == "-i":
            input_keymap_file = a
        elif o == "-o":
            output_keymap_file = a
        else:
            assert False, 'unhandled option'


    unicodemap = syscons.UnicodeMap()

    # read and parse unicode map files
    for unicode_map_file in unicode_map_files:
        umf = open(unicode_map_file, "r")
        linenum = 0
        for line in umf:
            linenum += 1

            try:
                unicodemap.addEntry(mapline = line)
            except ValueError, err:
                print >> sys.stderr, 'Error in line {0:d}'.format(linenum)
        umf.close()


    # read and parse input keymap file
    if input_keymap_file:
        ikf = open(input_keymap_file, "r")
    else:
        ikf = sys.stdin

    if output_keymap_file:
        okf = open(output_keymap_file, "w")
    else:
        okf = sys.stdout


    try:
        linenum = 0
        for line in ikf:
            linenum += 1

            keyent = syscons.KeyEntry(keyline = line)
            if keyent.scancode != None:
                okf.write('{0}\n'.format(keyent.remap(unicodemap)))
                continue

            accent = syscons.AccentEntry(mapline = line)
            if accent.name != None:
                okf.write('{0}\n'.format(accent.remap(unicodemap)))
                continue

            okf.write(line)
    finally:
        if ikf is not sys.stdin:
            ikf.close()
        if okf is not sys.stdin:
            okf.close()

    sys.exit(0)
